package com.attendance.www.hr.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;

import com.attendance.www.hr.beans.AttachmentBean;
import com.attendance.www.hr.dao.mapper.CorporationExtMapper;
import com.attendance.www.hr.dao.mapper.CorporationMapper;
import com.attendance.www.hr.dao.mapper.SystemConfigureMapper;
import com.attendance.www.hr.entitys.Corporation;
import com.attendance.www.hr.entitys.CorporationExample;
import com.attendance.www.hr.entitys.SystemConfigure;
import com.attendance.www.hr.entitys.SystemConfigureExample;
import com.attendance.www.hr.exception.ResultFaultException;
import com.attendance.www.hr.service.ICorporationExcelService;

@Service
public class CorporationExcelServiceImpl implements ICorporationExcelService {

	@Resource
	private CorporationMapper corporationDao;
	@Resource
	private CorporationExtMapper corporationExtDao;
	@Resource
	private SystemConfigureMapper systemConfigureDao;

	private Map<String, Integer> addCorporationMap;

	private Map<String, Integer> originalCorporationMap;

	private Map<String, Corporation> corporationMap;

	/**
	 * 删除公司相关数据
	 * 
	 * @return
	 */
	@Override
	public boolean delCorporation() {
		return true;
	}

	@Override
	public List<String> importCorporation(Workbook work, AttachmentBean attachmentBean) {
		if(attachmentBean.getType()==3) {
			SystemConfigure systemConfigure = systemConfigureDao.selectByExample(new SystemConfigureExample()).get(0);
			Date effectiveDate = systemConfigure.getEffectiveDate();
			if(effectiveDate!=null) {
				if(attachmentBean.getFromDate().getTime()-effectiveDate.getTime()>=0) {
					SystemConfigure systemConfigure1 =new SystemConfigure();
					systemConfigure1.setEffectiveDate(attachmentBean.getFromDate());
					systemConfigureDao.updateByExampleSelective(systemConfigure1, new SystemConfigureExample());
				}
			}
		}
		Calendar calendar = Calendar.getInstance(); // 得到日历
		calendar.setTime(attachmentBean.getFromDate());// 把当前时间赋给日历
		calendar.add(Calendar.DAY_OF_MONTH, -1); // 设置为前一天
		Date ThruDate = calendar.getTime(); // 得到前一天的时间
		Date oldThruDate = null;
		if (attachmentBean.getType() == 3) {
			CorporationExample example = new CorporationExample();
			CorporationExample.Criteria criteria = example.createCriteria();
			criteria.andThruDateIsNull();
			Corporation corporation = new Corporation();
			corporation.setThruDate(ThruDate);
			corporationDao.updateByExampleSelective(corporation, example);
		}

		addCorporationMap = new HashMap<String, Integer>();

		corporationMap = new HashMap<String, Corporation>();

		originalCorporationMap = new HashMap<String, Integer>();

		List<String> successList = new ArrayList<String>();

		// 判断导入类型 1.覆盖 2.增量
		if (!(attachmentBean.getType() == 3)) {
			List<Corporation> corporationsList = corporationExtDao.getCorporationListByExcel(attachmentBean);
			for (Corporation corporation : corporationsList) {
				corporationMap.put(corporation.getCorporationCode(), corporation);
				addCorporationMap.put(corporation.getCorporationCode(), -1);
				oldThruDate = corporation.getThruDate();
			}
		}

		// 获取工作表的数量
		int sheetNum = work.getNumberOfSheets();
		// 遍历工作表 找出要导入的Excel表
		for (int m = 0; m < sheetNum; m++) {
			Sheet sh = work.getSheetAt(m);
			if (sh.getSheetName().equals("1.1公司")) {
				Sheet sheet = work.getSheetAt(m);
				List<String> errorMsgList = new ArrayList<String>();// 创建错误信息列表
				// 扫描Excel每行的每个单元格
				for (int i = 1; i <= sheet.getLastRowNum(); i++) {
					Corporation corporation = new Corporation();// 创建公司对象
					StringBuilder str = new StringBuilder("第" + (i + 1) + "行");
					Row row = sheet.getRow(i);
					// 如果一整行为空则忽略此行继续遍历
					if (row == null) {
						continue;
					}
					// 遍历某一行的所有列，如果此行每列都为空则跳过继续下一行
					boolean isNull = true;
					for (int c = 0; c < row.getLastCellNum(); c++) {
						if (row.getCell(c) == null || StringUtils.isBlank(row.getCell(c).toString())) {
							continue;
						} else {
							isNull = false;
						}
					}
					if (isNull) {
						continue;
					}
					if (oldThruDate != null) {
						if (oldThruDate.getTime() >= attachmentBean.getFromDate().getTime()) {
							corporation.setThruDate(oldThruDate);
						}
					}
					corporation.setFromDate(attachmentBean.getFromDate());

					if (attachmentBean.getType() == 1)
						if (row.getCell(0) != null && StringUtils.isNotBlank(row.getCell(0).toString())) {
							String corporationCode = row.getCell(0).toString();
							if (originalCorporationMap.containsKey(corporationCode)) {
								if (originalCorporationMap.get(corporationCode).intValue() > 0) {
									str.append("与第" + originalCorporationMap.get(corporationCode) + "行原公司编码("
											+ corporationCode + ")重复,");
								} else {
									str.append("原公司编码(" + corporationCode + ")已存在,");
								}
							} else {
								if (corporationMap.containsKey(corporationCode)) {
									corporation
											.setCorporationId(corporationMap.get(corporationCode).getCorporationId());
									corporation.setIsDelete(corporationMap.get(corporationCode).getIsDelete());
									originalCorporationMap.put(row.getCell(0).toString(), i + 1);
								} else {
									str.append("原公司编码不存在,");
								}
							}
						} else {
							str.append("原公司编码不能为空,");
						}

					// 判断第二列公司编码的合法性
					if (row.getCell(1) != null && StringUtils.isNotBlank(row.getCell(1).toString())) {
						String corporationCode = row.getCell(1).toString();
						corporation.setCorporationCode(corporationCode);
						if (attachmentBean.getType() == 1 && row.getCell(0) != null
								&& StringUtils.isNotBlank(row.getCell(0).toString())) {
							String oldCorporationCode = row.getCell(0).toString();
							if (addCorporationMap.containsKey(corporationCode)
									&& !oldCorporationCode.equals(corporationCode)) {
								if (addCorporationMap.get(corporationCode) > 0) {
									str.append("与第" + addCorporationMap.get(corporationCode) + "行公司编码("
											+ corporationCode + ")重复,");
								} else {
									str.append("公司编码(" + corporationCode + ")已存在,");
								}
							} else {
								addCorporationMap.put(corporation.getCorporationCode(), i + 1);
							}
						} else {
							if (addCorporationMap.containsKey(corporationCode)) {
								if (addCorporationMap.get(corporationCode) > 0) {
									str.append("与第" + addCorporationMap.get(corporationCode) + "行公司编码("
											+ corporationCode + ")重复,");
								} else {
									str.append("公司编码(" + corporationCode + ")已存在,");
								}
							} else {
								addCorporationMap.put(corporation.getCorporationCode(), i + 1);
							}
						}
					} else {
						str.append("现公司编码不能为空,");
					}

					// 判断第三列公司名称的合法性
					if (row.getCell(2) != null && StringUtils.isNotBlank(row.getCell(2).toString())) {
						corporation.setCorporationName(row.getCell(2).toString());
					} else {
						str.append("公司名称不能为空,");
					}

					// 第四列描述
					if (row.getCell(3) != null && StringUtils.isNotBlank(row.getCell(3).toString())) {
						corporation.setDescription(row.getCell(3).toString());
					}

					if (str.length() == new String("第" + (i + 1) + "行").length()) {
						// 判断导入类型 1.覆盖 2.增量
						boolean t = true;
						if (attachmentBean.getType() == 1) {
							corporation.setUpdateTime(new Date());
							corporation.setCreateTime(corporationMap.get(row.getCell(0).toString()).getCreateTime());
							corporationDao.updateByPrimaryKey(corporation);
							String success = str.toString() + "公司编码(" + corporation.getCorporationCode() + ")";
							successList.add(success);
							t = false;
						}
						if (t) {
							try {
								// 添加

								corporationDao.insertSelective(corporation);
							} catch (Exception e) {
								throw new ResultFaultException("7_00001");
							}
						}

						// 将ID更改为行数

						corporationMap.put(corporation.getCorporationCode(), corporation);
					} else {
						String errorStr = str.toString().substring(0, str.toString().length() - 1);
						errorMsgList.add(errorStr);
					}
				}
				if (errorMsgList.size() > 0) {
					throw new ResultFaultException("7_00001", errorMsgList);
				}

				if (successList.size() > 0) {
					successList.add(0, "公司导入完成,并覆盖数据如下：");
				} else {
					successList.add(0, "公司导入完成");
				}
				return successList;
			}
		}
		throw new ResultFaultException("7_00011");
	}
}
